<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '菜单',
    // #ifdef MP-ALIPAY
    enablePullDownRefresh: false,
    'mp-alipay': {
      allowsBounceVertical: 'NO',
      transparentTitle: 'always',
      titlePenetrate: 'YES',
      defaultTitle: '',
    },
    // #endif
  },
}
</route>
<template>
  <CustomNavbar :onSearchSuccess="handleSearchSuccess" />
  <view class="container">
    <scroll-view
      :scroll-top="scrollTop"
      :scroll-y="true"
      class="scroll-Y"
      refresher-enabled
      :refresher-triggered="isTriggered"
      @refresherrefresh="upper"
      @scrolltolower="lower"
    >
      <view style="align-items: center; width: 100%; height: 400rpx; text-align: center">
        <image
          style="width: 400rpx; height: 400rpx"
          :src="imageRef"
          mode="scaleToFill"
          @tap="startEnd"
        />
      </view>
      <view class="dish-list">
        <view
          class="book"
          v-for="(dish, index) in dishListRef"
          :key="index"
          @click="navigateToBook(dish.id)"
        >
          <image :src="dish.avatar" class="book-cover"></image>
          <text class="book-title">{{ dish.name }}</text>
        </view>
      </view>
      <NullView
        v-if="!dishListRef || dishListRef.length == 0"
        content="没有菜品"
        href="去添加~"
        url="/pages/my/dish/info"
      ></NullView>
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
import CustomNavbar from '../component/DishCustomNavbar.vue'
import NullView from '@/components/NullView.vue'
import { useUserStore } from '@/store'
import { dishListApi } from '@/service/dish'
import { Dish } from '@/types/dish'
import { getRandomNumber } from '@/utils/random'

const navigateToBook = (id: number) => {
  // 使用uni.navigateTo跳转到详情页面，并携带bookId参数
  uni.navigateTo({
    url: `/pages/my/dish/info?id=${id}`,
  })
}

let timer: number | null = null
const dishListRef = ref<Dish[]>([])
const scrollTop = ref(0)
const imageRef = ref<string>(dishListRef.value[0]?.avatar)
const currentTime = ref<string>(new Date().toLocaleTimeString())
const startFlag = ref(true)

onLoad(async () => {
  if (timer) {
    clearInterval(timer)
  }
  // 初始化加载数据
  const bookListRes = await dishListApi({ page: 1, size: 10 })
  dishListRef.value = bookListRes.data.records
  start()
})

const start = () => {
  timer = setInterval(() => {
    // 每秒钟执行的操作
    const index = getRandomNumber(0, dishListRef.value.length)
    const image = dishListRef.value[index].avatar
    imageRef.value = image
  }, 100)
}
const end = () => {
  if (timer) {
    clearInterval(timer) // 同样去掉window.
    timer = null
    console.log('定时器已清除')
  }
}

// 页面卸载时清除定时器，防止内存泄漏
onUnload(() => {
  end()
})
onShow(async () => {
  const bookListRes = await dishListApi({ page: 1, size: 10 })
  console.log(bookListRes.data.records)
  // for (const element of bookListRes.data.records) {
  //   element.avatar = element.avatar + (element.avatar.includes('?') ? '&' : '?') + 't=' + Date.now()
  // }
  dishListRef.value = bookListRes.data.records
})

const startEnd = () => {
  if (startFlag.value === true) {
    startFlag.value = false
    end()
  } else {
    startFlag.value = true
    start()
  }
}

// 3. 接收子组件的成功回调：更新菜品列表
const handleSearchSuccess = (list: Dish[]) => {
  dishListRef.value = list
}

// 触发下拉刷新
const upper = async () => {
  console.log('下拉刷新')
  isTriggered.value = true
  // 加载数据 api 要加 await
  // ...
  const bookListRes = await dishListApi({ page: 1, size: 10 })
  dishListRef.value = bookListRes.data.records
  setInterval(() => {
    isTriggered.value = false
  }, 1000)
}
const isTriggered = ref(false)

const lower = () => {
  console.log('lower')
  // guessRef.value?.getMore()
}
</script>

<style lang="scss">
.dish-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: start;
}
.book {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 26%; /* 可根据需要调整宽度 */
  margin: 10px;
}
.book-cover {
  width: 100%;
  height: 100px; /* 可根据需要调整高度 */
  object-fit: contain;
}
.book-title {
  margin-top: 10px;
  text-align: center;
}

.scroll-Y {
  width: 100%;
  height: calc(100vh - var(--window-top));
}
</style>
